#!/bin/bash

JENKINS_PLIST="/Library/LaunchDaemons/org.jenkins-ci.plist"

# Because PackageMaker just copies the components, we need to fix the permissions
chown root:wheel ${JENKINS_PLIST}
chmod 644 ${JENKINS_PLIST}
mkdir -p /Users/Shared/Jenkins
find /Users/Shared/Jenkins \( -not -user daemon -or -not -group daemon \) -print0 | xargs -0 chown daemon:daemon

# Create log directory, which can be written by Jenkins daemon
mkdir -p /var/log/jenkins
chown daemon:daemon /var/log/jenkins

# Enable log rotation by newsyslog
cat <<_EOT_ > /etc/newsyslog.d/jenkins.conf
# logfilename          [owner:group]    mode count size when  flags [/pid_file] [sig_num]
# Rotate jenkins log at midnight, and preserve old logs in 3 days
/var/log/jenkins/jenkins.log            644  3     *    \$D0   J
_EOT_

# Load and start the launch daemon
/bin/launchctl load -w ${JENKINS_PLIST}

# Wait for port 8080 to start accepting connections.
# But don't wait forever.
timeout=$(($(date +%s) + 60))
while [ $(date +%s) -lt $timeout ] && ! curl -s http://localhost:8080 >/dev/null; do
    sleep 1
done

if [ $(date +%s) -ge $timeout ]; then
    echo "Timed out waiting for Jenkins port 8080 to start listening!"
    echo "Either Jenkins did not load or this system is very slow."
fi
